package server;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import logic.Order;
import logic.SystemMesseges;

import ocsf.server.ConnectionToClient;

import GUI.Client_GUI;

public class MessageController {
	private DB_Manager DB;
	private OBL_Server parent;
	
	public MessageController(OBL_Server parent,DB_Manager DB) {
		this.parent = parent;
		this.DB = DB;
	}
	
	
	
	
	
	
	
	
	
	public static void masendmail() throws AddressException, MessagingException
	   {    
		String host = "smtp.gmail.com";
	    String from = "obllibraryg12";
	    String pass = "oblg12obl";
	    Properties props = System.getProperties();
	    props.put("mail.smtp.starttls.enable", "true"); // added this line
	    props.put("mail.smtp.host", "localhost");
	    props.put("mail.smtp.user", from);
	    props.put("mail.smtp.password", pass);
	    props.put("mail.smtp.port", "587");
	    props.put("mail.smtp.auth", "true");

	    String[] to = {"mail.adidahan@gmail.com"}; // added this line

	    Session session = Session.getDefaultInstance(props, null);
	    MimeMessage message = new MimeMessage(session);
	    message.setFrom(new InternetAddress(from));

	    InternetAddress[] toAddress = new InternetAddress[to.length];

	    // To get the array of addresses
	    for( int i=0; i < to.length; i++ ) { // changed from a while loop
	        toAddress[i] = new InternetAddress(to[i]);
	    }
	    System.out.println(Message.RecipientType.TO);

	    for( int i=0; i < toAddress.length; i++) { // changed from a while loop
	        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
	    }
	    message.setSubject("reminder !!!!!!!!!");
	    message.setText("Welcome to JavaMail");
	    Transport transport = session.getTransport("smtp");
	    transport.connect(host, from, pass);
	    transport.sendMessage(message, message.getAllRecipients());
	    transport.close();
	   }
	
	
	
	
	
	
	
	
	

	/**
	 * this function gets id value
	 * id can be a member id (or a privilege level - since there is no overlap between those) 
	 * @param id - the UID/PRIVILIGE value
	 * @return ArrayList<SystemMessages> contatining all the UNDELETED SystemMessages for the entered ID
	 */
	public ArrayList<SystemMesseges> GetSystem_Message(int id,ConnectionToClient client)
	{
	
			String query = "SELECT * FROM systemmessages WHERE UID = ";
			query+= id;
			query += " AND MSGTYPE = " + SystemMesseges.SYSTEM_MESSAGE + " AND 'READMSG' != " + SystemMesseges.MESSAGE_DELETED + ";";
			
			ResultSet rs = DB.Query(query);
			ArrayList<SystemMesseges> msgs =  SeralizeResultSet(rs);
			
			if (client != null){
				ArrayList<String> indexes = new ArrayList<String>();
				ArrayList<Object> data = new ArrayList<Object>();
				
				indexes.add("MESSAGES");
				data.add(msgs);
				
				int action = logic.Message.GET_MESSAGES_RESPONSE;
				
				logic.Message toSend = new logic.Message(indexes, data, action);
				
				try{
					client.sendToClient(toSend);
				}catch(IOException e){
					//TODO handle this error
				}
			}
			return msgs;
	}
	
	
	/**
	 * This Function convert a ResultSet into ArrayList<SystemMesseges> for  MessageS
	 * (ResultSet is not seralizeable)
	 * @param rs - the ResultSet to conver
	 * @return - ArrayList<SystemMesseges> which conatins all MessageS
	 */
	public ArrayList<SystemMesseges> SeralizeResultSet(ResultSet rs){
		
		ArrayList<SystemMesseges> MessageList = new ArrayList<SystemMesseges>();

		try{
			while(rs.next()){
				//SystemMesseges(int MID, int UID,String MESSAGE, int TYPE,String DATE,int READ,String TITLE)
				SystemMesseges sysmessage = new SystemMesseges(rs.getInt("MSID"),rs.getInt("UID"),rs.getString("MESSAGE"),
						rs.getInt("MSGTYPE"),rs.getString("MSGDATE"),rs.getInt("READMSG"),rs.getString("TITLE"));
				MessageList.add(sysmessage);
				}
			
			return MessageList;
		}catch(SQLException e){
			//TODO handle serialize error
			return null;
		}
	}
	
	
	/**
	 * This function creates a new SystemMessage and notifys the client
	 * @param data - ArrayList<String> containing the Message data
	 * @return 1 for success, 0 otherwise
	 */
	public int CreateMessage(ArrayList<Object> data,ConnectionToClient client){
	
	
	String query = "INSERT INTO systemmessages " +
		"(MSID,UID,TITLE,MESSAGE,MSGTYPE,MSGDATE,READMSG) VALUES" +
			"(null,'" + data.get(0) + "','" + data.get(1) + "','" + data.get(2) + "','" 
				+ data.get(3) +  "','" + data.get(4) + "','" + SystemMesseges.MESSAGE_UNREAD + "')";

	if (DB.Update(query) == 0){
		//TODO handle this error
		return 0;
	}
	
	//TODO notify client for new SystemMessage
	
	return 1;
}
	


	/**
	 * this function update the status of the messages to already read 
	 **@param msg  is an array of messages to update
	 * @param client return the result
	 */
	public void DeleteMessage(logic.Message msg ,ConnectionToClient client)
	{
		ArrayList<Object> info = msg.GetMessageData();
		int mid = (Integer)info.get(0);
		
		String updateQuery = "UPDATE systemmessages SET MSGTYPE = " + SystemMesseges.MESSAGE_DELETED + " WHERE MSID = " + mid + ";";

		if (DB.Update(updateQuery) == 0){
			//TODO handle this error

		}	
	}
	
	/**
	 * this function update the status of the messages to already read 
	 **@param msg  is an array of messages to update
	 * @param client return the result
	 */
	public void SetReadMessage(logic.Message msg ,ConnectionToClient client){
		ArrayList<Object> info = msg.GetMessageData();
		int mid = (Integer)info.get(0);
		
		String updateQuery = "UPDATE systemmessages SET READMSG = '" + SystemMesseges.MESSAGE_READ + "' WHERE MSID = '" + mid + "';";

		if (DB.Update(updateQuery) == 0){
			//TODO handle this error

		}	
	}
	
	
	
	
	/**
	 * This function sends an Email message to client
	 * @param Destination - target email addres
	 * @param Msg - the message content
	 * @param title - the message title
	 */
	public void SendMail(String Destination,String Msg,String title)
	{
		String host = "smtp.gmail.com";
	    String from = "obllibraryg12";
	    String pass = "oblg12obl";
	    Properties props = System.getProperties();
	    props.put("mail.smtp.starttls.enable", "true"); // added this line
	    props.put("mail.smtp.host", host);
	    props.put("mail.smtp.user", from);
	    props.put("mail.smtp.password", pass);
	    props.put("mail.smtp.port", "587");
	    props.put("mail.smtp.auth", "true");

	    String[] to = {Destination}; // added this line

	    try{
		    Session session = Session.getDefaultInstance(props, null);
		    MimeMessage message = new MimeMessage(session);
		    message.setFrom(new InternetAddress(from));

		    InternetAddress[] toAddress = new InternetAddress[to.length];

		    // To get the array of addresses
		    for( int i=0; i < to.length; i++ ) { // changed from a while loop
		        toAddress[i] = new InternetAddress(to[i]);
		    }

		    for( int i=0; i < toAddress.length; i++) { // changed from a while loop
		        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
		    }

		    message.setSubject(title);
		    message.setText(Msg);
		    Transport transport = session.getTransport("smtp");
		    transport.connect(host, from, pass);
		    transport.sendMessage(message, message.getAllRecipients());
		    transport.close();
	    }catch(AddressException e){
	    	//TODO handle this error
	    }catch(MessagingException e){
	    	//TODO handle this error
	    }

	   }
}
